package com.laicunba.event.listener;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.D2HEvent;
import com.laicunba.pojo.CashCouponDefDO;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.CashCouponDefService;
import com.laicunba.service.FinancingTargetBidService;
import com.laicunba.service.MobileMessageService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.TemplateService;
import com.laicunba.service.UserService;

@Component
public class D2HListener implements ApplicationListener<D2HEvent> {
	private static final Logger LOG = Logger.getLogger(D2HListener.class);

	@Autowired
	private CashCouponDefService cashCouponDefService;
	@Autowired
	private UserService userService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private MobileMessageService mobileMessageService;
	@Autowired
	private RegistryService registryService;
	@Autowired
	private FinancingTargetBidService financingTargetBidService;

	@Override
	public void onApplicationEvent(D2HEvent event) {
		try {
			FinancingTargetBidDO bidDO = financingTargetBidService.get(FinancingTargetBidDO.class, String.valueOf(event.getSource()));
			if(bidDO != null && financingTargetBidService.countFixBid2Demand(bidDO.getBidUserId()) == 0) {
				CashCouponDefDO couponDef = cashCouponDefService.get(CashCouponDefDO.class, "firsttime-fix2demand-red-package-5");
				if (couponDef == null) {
					LOG.warn("首次使用定转活送现金券,但找不到现金券模版");
					return;
				}
				cashCouponDefService.send2UserWithMessage("firsttime-fix2demand-red-package-5", bidDO.getBidUserId(), true, "首次成功使用定转活送5元现金券");
				UserDO bidUser = userService.get(UserDO.class, bidDO.getBidUserId());
				if(bidUser != null) {
					TemplateDO templateDO = templateService.findByCodeWidthDefault("FIX_BID_2_DEMAND_FIRST_TIME");
					Map<String, Object> paremeter = new HashMap<String, Object>();
					paremeter.put("cashCouponName", couponDef.getAmount().toString() + "元现金券");
					String content = templateService.simpleMerge(templateDO.getContent(), paremeter);
					mobileMessageService.sendMsgAsync(bidUser.getMobile(), content);
					LOG.info(String.format("用户[%s]首次成功使用定转活送5元现金券,发放5元现金券", bidUser.getMobile()));
				}
			}
		} catch (Exception e) {
			LOG.error("用户首次成功使用定转活发放现金券异常", e);
		}
	}
}
